package org.niugang.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.niugang.security.common.enums.ExceptionEnum;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录失败回调函数
 * @author Created by niugang on 2019/5/23/14:55
 */
@SuppressWarnings("Duplicates")
@Component
@Slf4j
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        log.info("Login fail");

        Map<String, Object> map = new HashMap<>(4);
        map.put("message", "用户名或密码错误");
        map.put("status", ExceptionEnum.USERNAME_OR_PASSWORD_ERROR.value());
        map.put("timestamp", System.currentTimeMillis());
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        //505 错误码 用户名或密码错误
        response.setStatus(ExceptionEnum.USERNAME_OR_PASSWORD_ERROR.value());
        response.getWriter().write(objectMapper.writeValueAsString(map));


    }
}
